package com.im.db;

import java.util.List;

import com.core.sdk.core.BaseEvent;
import com.core.sdk.core.BaseService;
import com.google.inject.Inject;
import com.im.db.event.XmppMessageRequestEvent;
import com.im.db.event.XmppMessageRequestEvent.Operate;
import com.im.db.event.XmppMessageResponseEvent;
import com.im.model.XmppMessage;

public class DBManagerService extends BaseService {

	@Inject
	XmppMessageDao xmppMessageDao;

	@Inject
	DBHelper dbHelper;
	
	@Override
	protected void doCreate() {
		
	}
	
	@Override
	protected void doExecuteEvent(BaseEvent evt) {
		super.doExecuteEvent(evt);
		if(evt instanceof XmppMessageRequestEvent){
			procressXmppMessageRequestEvent((XmppMessageRequestEvent)evt);
		}
	}
	
	private void procressXmppMessageRequestEvent(XmppMessageRequestEvent event){
		Operate op = event.getOp();
		if(op == Operate.loadHistory){
			String otherJID = event.getParam().getOtherUser();
			long pageNo = event.getParam().getPageNo();
			long pageSize = event.getParam().getPageSize();
			long time = event.getParam().getTime();
			List<XmppMessage> result = xmppMessageDao.getHistoryXmppMessage(otherJID,pageNo,pageSize,time);
			XmppMessageResponseEvent resp = new XmppMessageResponseEvent(event.getFrom(),op,result);
			resp.setPageNo(pageNo);
			sendEvent(resp);
		}else if(op == Operate.markToReaded){
			List<String> ids = event.getParam().getIds();
			if(ids != null && ids.size() > 0){
				xmppMessageDao.markToReadedById(ids.toArray(new Object[ids.size()]));
			}
		}else if(op == Operate.unread){
			String otherJID = event.getParam().getOtherUser();
			List<XmppMessage> result = xmppMessageDao.getUnreadXmppMessage(otherJID);
			XmppMessageResponseEvent resp = new XmppMessageResponseEvent(event.getFrom(),op,result);
			sendEvent(resp);
		}
	}

	@Override
	protected void doDestroy() {
		dbHelper.close();
	}
}
